package com.czl.module_service.activity

import android.content.Intent
import android.text.TextUtils
import android.view.View
import android.widget.*
import com.alibaba.android.arouter.facade.annotation.Route
import com.czl.base.base.BaseActivity
import com.czl.base.config.AppConstants
import com.czl.module_service.BR
import com.czl.module_service.R
import com.czl.module_service.databinding.ActivityAddHealthReportBinding
import com.czl.module_service.viewmodel.AddHealthReportViewModel
import com.czl.base.data.bean.tengyun.HealthUserBean
import com.czl.base.event.LiveBusCenter
import java.util.*
import android.widget.RadioGroup
import com.annimon.stream.Collectors
import com.annimon.stream.Stream
import com.bigkoo.pickerview.view.TimePickerView
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.TimeUtils
import com.czl.base.data.bean.tengyun.HealthReportBean
import com.czl.base.util.DialogHelper
import android.widget.TextView
import com.czl.base.data.bean.RoomBean
import com.czl.module_service.view.flowlayout.FlowLayout

import com.czl.module_service.view.flowlayout.TagAdapter
import com.lxj.xpopup.util.KeyboardUtils
import kotlin.collections.ArrayList


@Route(path = AppConstants.Router.Service.F_ADD_HEALTH_REPORT)
class AddHealthReportActivity : BaseActivity<ActivityAddHealthReportBinding, AddHealthReportViewModel>() {

    private lateinit var pvTime: TimePickerView
    var healthType = 0
    var bean: HealthUserBean.Data? = null
    private var healthBean = HealthReportBean.Data()
    private var tagAdapter: TagAdapter<HealthReportBean.FamilyData>? = null
    var mTags: ArrayList<HealthReportBean.FamilyData> = arrayListOf()
    var lastRadioButton: RadioButton? = null
    var roomList: List<RoomBean>? = null

    override fun initContentView(): Int {
        return R.layout.activity_add_health_report
    }

    override fun initVariableId(): Int {
        return BR.viewModel
    }

    override fun initData() {
        viewModel.tvTitle.set("健康上报")
//        viewModel.getAreaByUser()
        viewModel.getUserRooms()
        setTagAdapter()
        // 跳转房间信息
        /*binding.etAddress.setOnClickListener {
//            startContainerActivity(AppConstants.Router.Room.F_MYROOM)
            viewModel.onSwitchAreaCommand
        }*/
        // 跳转亲属上报
        binding.btnRelation.setOnClickListener {
            val intent = Intent(applicationContext, AddFamilyHealthActivity::class.java)
            startActivity(intent)
        }
        var list = arrayListOf<RadioButton>()
        for (index in 1..binding.radioGroupId1.childCount){
            list.add(binding.radioGroupId1.getChildAt(index -1) as RadioButton)
        }
        for (index in 1..binding.radioGroupId2.childCount){
            list.add(binding.radioGroupId2.getChildAt(index -1) as RadioButton)
        }
        for (v in list) {
            lastRadioButton = list[0]
            v.setOnClickListener{v1: View ->
                KeyboardUtils.hideSoftInput(v)
                if (lastRadioButton?.id != v1.id) {
                    lastRadioButton?.apply {
                        isChecked = false
                    }
                }
                lastRadioButton = v
                if (v.id == R.id.rb1 || v.id == R.id.rb5 || v.id == R.id.rb6) {
                    healthType = if (v.id == R.id.rb1) 0 else if (v.id == R.id.rb5) 4 else 5
                    findViewById<LinearLayout>(R.id.ll_visibility).visibility = View.GONE
                    findViewById<LinearLayout>(R.id.ll_visibility1).visibility = View.GONE
                    findViewById<LinearLayout>(R.id.ll_visibility2).visibility = View.GONE
                }
                if (v.id == R.id.rb2) {
                    healthType = 1
                    findViewById<LinearLayout>(R.id.ll_visibility).visibility = View.VISIBLE
                    findViewById<LinearLayout>(R.id.ll_visibility1).visibility = View.GONE
                    findViewById<LinearLayout>(R.id.ll_visibility2).visibility = View.GONE
                    val rg3 = findViewById<RadioGroup>(R.id.radioGroupId5)
                    healthBean.admitted = 1
                    rg3.setOnCheckedChangeListener { group, checkedId ->
                        KeyboardUtils.hideSoftInput(rg3)
                        val checkedRadioButton = group?.findViewById(group.checkedRadioButtonId) as? RadioButton
                        checkedRadioButton?.let {
                            if (checkedRadioButton.isChecked) {
                                if (checkedRadioButton.id == R.id.rb11) {
                                    healthBean.admitted = 1
                                } else if (checkedRadioButton.id == R.id.rb12) {
                                    healthBean.admitted = 0
                                }
                            }

                        }
                    }
                }
                if (v.id == R.id.rb3) {
                    healthType = 2
                    findViewById<LinearLayout>(R.id.ll_visibility).visibility = View.GONE
                    findViewById<LinearLayout>(R.id.ll_visibility1).visibility = View.VISIBLE
                    findViewById<LinearLayout>(R.id.ll_visibility2).visibility = View.GONE
                    val rg4 = findViewById<RadioGroup>(R.id.radioGroupId6)
                    healthBean.admitted = 1
                    rg4.setOnCheckedChangeListener { group, checkedId ->
                        KeyboardUtils.hideSoftInput(rg4)
                        val checkedRadioButton = group?.findViewById(group.checkedRadioButtonId) as? RadioButton
                        checkedRadioButton?.let {
                            if (checkedRadioButton.isChecked) {
                                if (checkedRadioButton.id == R.id.rb13) {
                                    healthBean.admitted = 1
                                } else if (checkedRadioButton.id == R.id.rb14) {
                                    healthBean.admitted = 0
                                }
                            }

                        }
                    }
                }
                if (v.id == R.id.rb4) {
                    healthType = 3
                    findViewById<LinearLayout>(R.id.ll_visibility).visibility = View.GONE
                    findViewById<LinearLayout>(R.id.ll_visibility1).visibility = View.GONE
                    findViewById<LinearLayout>(R.id.ll_visibility2).visibility = View.VISIBLE
                    val rg5 = findViewById<RadioGroup>(R.id.radioGroupId7)
                    healthBean.admitted = 1
                    rg5.setOnCheckedChangeListener { group, checkedId ->
                        KeyboardUtils.hideSoftInput(rg5)
                        val checkedRadioButton = group?.findViewById(group.checkedRadioButtonId) as? RadioButton
                        checkedRadioButton?.let {
                            if (checkedRadioButton.isChecked) {
                                if (checkedRadioButton.id == R.id.rb15) {
                                    healthBean.admitted = 1
                                } else if (checkedRadioButton.id == R.id.rb16) {
                                    healthBean.admitted = 0
                                }
                            }

                        }
                    }
                    // 确诊症状
                    val rg6 = findViewById<RadioGroup>(R.id.radioGroupId8)
                    healthBean.confirmed = 1
                    rg6.setOnCheckedChangeListener { group, checkedId ->
                        KeyboardUtils.hideSoftInput(rg6)
                        val checkedRadioButton = group?.findViewById(group.checkedRadioButtonId) as? RadioButton
                        checkedRadioButton?.let {
                            if (checkedRadioButton.isChecked) {
                                if (checkedRadioButton.id == R.id.rb17) {
                                    healthBean.confirmed = 1
                                } else if (checkedRadioButton.id == R.id.rb18) {
                                    healthBean.confirmed = 0
                                }
                            }
                        }
                    }
                }
            }
        }
        // 疑似接触
        val rg = findViewById<RadioGroup>(R.id.radioGroupId3)
        healthBean.touching = 0
        rg.setOnCheckedChangeListener { group, checkedId ->
            KeyboardUtils.hideSoftInput(rg)
            val checkedRadioButton = group?.findViewById(group.checkedRadioButtonId) as? RadioButton
            checkedRadioButton?.let {
                if (checkedRadioButton.isChecked) {
                    if (checkedRadioButton.id == R.id.rb7) {
                        healthBean.touching = 1
                        findViewById<LinearLayout>(R.id.ll_visibility4).visibility = View.VISIBLE
                        pvTime =
                            DialogHelper.showDatePickDialog(this, "日期", Calendar.getInstance(), null, Calendar.getInstance()) { date, _ ->
                                binding.tvTouchTime.text = TimeUtils.date2String(date, "yyyy-MM-dd")
                            }
                    } else if (checkedRadioButton.id == R.id.rb8) {
                        healthBean.touching = 0
                        findViewById<LinearLayout>(R.id.ll_visibility4).visibility = View.GONE
                    }
                }

            }
        }
        val rg2 = findViewById<RadioGroup>(R.id.radioGroupId4)
        healthBean.lifeDifficulties = 0
        rg2.setOnCheckedChangeListener { group, checkedId ->
            KeyboardUtils.hideSoftInput(rg2)
            val checkedRadioButton = group?.findViewById(group.checkedRadioButtonId) as? RadioButton
            checkedRadioButton?.let {
                if (checkedRadioButton.isChecked) {
                    if (checkedRadioButton.id == R.id.rb9) {
                        healthBean.lifeDifficulties = 1
                        findViewById<LinearLayout>(R.id.ll_visibility6).visibility = View.VISIBLE
                    } else if (checkedRadioButton.id == R.id.rb10) {
                        healthBean.lifeDifficulties = 0
                        findViewById<LinearLayout>(R.id.ll_visibility6).visibility = View.GONE
                    }
                }

            }
        }
        // 新增疫情上报
        binding.btnCommit.setOnClickListener {
            if (binding.cbSure.isChecked) {
                healthBean.apply {
                    userName = viewModel.userInfo?.name.toString()
                    idCard = viewModel.userInfo?.idCard.toString()
                    phone = viewModel.userInfo?.phone.toString()
                    province = "广东省"
                    city = "深圳市"
                    community = viewModel.areaName
                    neighName = viewModel.areaName
                    healthyType = healthType
                    temperature = binding.etTemp.text.toString()
                }
                if (healthBean.healthyType == 0 || healthBean.healthyType == 4 || healthBean.healthyType == 5) {
                    healthBean.admitted = null
                    healthBean.confirmed = null
                }
                if (healthBean.healthyType == 1) {
                    healthBean.suspected = ""
                    healthBean.confirmed = null
                }
                if (healthBean.healthyType == 3) {
                    healthBean.suspected = ""
                }
                if (healthBean.healthyType == 2) {
                    // 疑似症状
                    val suspected = mutableListOf <Any>()
                    if (binding.cb1.isChecked) suspected.add(binding.cb1.text as String)
                    if (binding.cb2.isChecked) suspected.add(binding.cb2.text as String)
                    if (binding.cb3.isChecked) suspected.add(binding.cb3.text as String)
                    if (binding.cb4.isChecked) suspected.add(binding.cb4.text as String)
                    healthBean.suspected = ""
                    healthBean.suspected = TextUtils.join("、", suspected)
                }
                if (healthBean.touching == 1) {
                    healthBean.touchingTime = binding.tvTouchTime.text.toString()
                    healthBean.touchingName = binding.tvTouchName.text.toString()
                    healthBean.touchingPhone = binding.tvTouchPhone.text.toString()
                }
                if (healthBean.lifeDifficulties == 1) {
                    // 困难类型
                    val suspected = mutableListOf <Any>()
                    if (binding.cb5.isChecked) suspected.add(binding.cb5.text as String)
                    if (binding.cb6.isChecked) suspected.add(binding.cb6.text as String)
                    if (binding.cb7.isChecked) suspected.add(binding.cb7.text as String)
                    if (binding.cb8.isChecked) suspected.add(binding.cb8.text as String)
                    if (binding.cb9.isChecked) suspected.add(binding.cb9.text as String)
                    healthBean.difficulties = ""
                    healthBean.difficulties = TextUtils.join("、", suspected)
                }
                viewModel.addHealthyReport(healthBean)
            } else {
                showErrorToast("请勾选本人郑重承诺")
            }
        }
    }

    private fun setTagAdapter() {
        tagAdapter = object : TagAdapter<HealthReportBean.FamilyData>(mTags) {
            override fun getView(parent: FlowLayout?, position: Int, tag: HealthReportBean.FamilyData): View? {
                val view = View.inflate(this@AddHealthReportActivity, R.layout.layout_tag_name, null)
                val tvName = view.findViewById<TextView>(R.id.tv_relationName)
                tvName.text = tag.relativesName
                val ivDel = view.findViewById<ImageView>(R.id.iv_delete)
                ivDel.setOnClickListener {
                    mTags.remove(tag)
                    healthBean.healthyRelativesInfoList = mTags
                    tagAdapter?.notifyDataChanged()
                }
                return view
            }
        }
        binding.tflTag.adapter = tagAdapter
    }
    override fun initViewObservable() {
        LiveBusCenter.observeAddRelationHealthyEvent(this, {
            LogUtils.e("----->" + it.relationData)
            if (it.relationData != null) {
                healthBean.healthyRelativesInfoList.add(it.relationData as HealthReportBean.FamilyData)
                mTags.add(it.relationData as HealthReportBean.FamilyData)
                tagAdapter?.notifyDataChanged()
            }
        })
//        选择地点
        viewModel.uc.switchAreaEvent.observe(this, {
            val viewBinding: ActivityAddHealthReportBinding = binding
            roomList?.let {
                DialogHelper.showBottomListDialog(
                    this,
                    Stream.of(it).map { t -> t.houseCode }.withoutNulls()
                        .collect(Collectors.toList()) as ArrayList<String>
                ) { position, text ->
                    viewBinding.etAddress.text = text
                    healthBean.address = text
                    healthBean.houseId = it[position].houseId
                }
            }
        })

//        接触日期选择
        viewModel.uc.choiceBirthdayEvent.observe(this, {
            if (binding.tvTouchTime.text.toString().matches(Regex("^\\d*-\\d*-\\d*\$"))){
                val date = binding.tvTouchTime.text.toString().split("-")
                pvTime.setDate(Calendar.getInstance().apply { this[date[0].toInt(),(date[1].toInt()-1)]=date[2].toInt() })
            }
            KeyboardUtils.hideSoftInput(binding.tvTouchTime)
            pvTime.show()
        })
        viewModel.uc.loadCompleteEvent.observe(this, { data ->
            // 前一页跳转对象数据
            bean = data
        })
        viewModel.uc.loadRoomsEvent.observe(this,{
            val viewBinding: ActivityAddHealthReportBinding = binding
            viewBinding.etName.text = viewModel.userInfo?.name
            viewBinding.etIdCard.text = viewModel.userInfo?.idCard
            viewBinding.etPhone.text = viewModel.userInfo?.phone
            viewBinding.etProvince.text = "广东省"
            viewBinding.etCity.text = "深圳市"
            viewBinding.etCommunity.text = viewModel.areaName
            if (it.isNullOrEmpty())return@observe
            roomList = it
            viewBinding.etAddress.text = it[0].houseCode
            healthBean.address = it[0].houseCode
            healthBean.houseId = it[0].houseId
            /*var roomNum= Stream.of(it).map { r->r.houseCode }.withoutNulls().collect(Collectors.toList())
            roomNum?.let {
                val rs = TextUtils.join("、", roomNum)
                viewBinding.etAddress.setText(rs)
                healthBean.address = rs
            }*/
        })
    }
}
